package com.zyl.pagergallerymoredemo_java.fragment;

import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.zyl.pagergallerymoredemo_java.R;
import com.zyl.pagergallerymoredemo_java.adapter.GalleryAdapter;
import com.zyl.pagergallerymoredemo_java.adapter.PhotoAdapter;
import com.zyl.pagergallerymoredemo_java.pojo.Pixabay;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

public class PhotoFragment extends Fragment {
    public static final int REQUEST_WRITE_EXTERNAL_STORAGE = 1;

    private ViewPager2 viewPager2;
    private TextView tvNumber;
    private ImageView saveImage;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_photo, container, false);
        viewPager2 = view.findViewById(R.id.viewPager2);
        tvNumber = view.findViewById(R.id.tv_number);
        saveImage = view.findViewById(R.id.saveImage);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        PhotoAdapter photoAdapter = new PhotoAdapter();
        viewPager2.setAdapter(photoAdapter);

        final ArrayList parcelableArrayList = getArguments().getParcelableArrayList(GalleryAdapter.PHOTO_LIST);
        int anInt = getArguments().getInt(GalleryAdapter.PHOTO_POSITION);

        photoAdapter.submitList(parcelableArrayList);

        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                tvNumber.setText(position + 1 + " / " + parcelableArrayList.size());
            }
        });

        viewPager2.setCurrentItem(anInt, false);


        saveImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT < 29
                        && ContextCompat.checkSelfPermission(requireContext(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            REQUEST_WRITE_EXTERNAL_STORAGE
                    );
                } else {
                    savePhoto();
                }

            }
        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_WRITE_EXTERNAL_STORAGE) {
            if (grantResults != null && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                savePhoto();
            } else {
                Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void savePhoto() {
        try {
            RecyclerView recyclerView = (RecyclerView) viewPager2.getChildAt(0);
            PhotoAdapter.PhotoViewHolder viewHolder = (PhotoAdapter.PhotoViewHolder) recyclerView.findViewHolderForAdapterPosition(viewPager2.getCurrentItem());
//            Bitmap bitmap = DrawableToBitmap(viewHolder.photoView.getDrawable());
            Bitmap bitmap = ((BitmapDrawable) viewHolder.photoView.getDrawable()).getBitmap();
            Uri saveUri = requireContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new ContentValues());
            OutputStream outputStream = requireContext().getContentResolver().openOutputStream(saveUri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
            Toast.makeText(requireContext(), "存储成功", Toast.LENGTH_SHORT).show();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show();
            Log.e("myTAG", "savePhoto: ", e);
        }

    }


    //Drawable 转 Bitmap
    public static Bitmap DrawableToBitmap(Drawable drawable) {

        // 获取 drawable 长宽
        int width = drawable.getIntrinsicWidth();
        int heigh = drawable.getIntrinsicHeight();

        drawable.setBounds(0, 0, width, heigh);

        // 获取drawable的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 创建bitmap
        Bitmap bitmap = Bitmap.createBitmap(width, heigh, config);
        // 创建bitmap画布
        Canvas canvas = new Canvas(bitmap);
        // 将drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }
}
